'use strict';

const { Service } = require('egg');
const {Solar, Lunar, HolidayUtil} = require('lunar-javascript')
const ModelName = 'Address'

function getBaZiValue(data) {
  let bazi = null
  // 1.年月日时是最完整的。2，年月日，3.年
  // 假设有一个生日日期
  let lunar = null
  let birthday = '';
  if (data.year) {
    birthday = data.year
    if (data.month) {
      birthday = birthday + '-' + data.month
      if (data.day) {
        birthday = birthday + '-' + data.day
        lunar = Lunar.fromDate(new Date(birthday));
        console.log('日',birthday,'lunar.getBaZi()', lunar.getBaZi())
        bazi = lunar.getBaZi().splice(0,3)
        if (data.hour) {
          birthday = birthday + ' ' + data.hour + ':00:00'
          lunar = Lunar.fromDate(new Date(birthday));
          console.log('时',birthday,'lunar.getBaZi()', lunar.getBaZi())
          bazi = lunar.getBaZi()
        }
      } else {
        lunar = Lunar.fromDate(new Date(birthday));
        console.log('月',birthday,'lunar.getBaZi()', lunar.getBaZi())
        bazi = lunar.getBaZi().splice(0, 1);
      }
    } else {
      lunar = Lunar.fromDate(new Date(birthday));
      console.log('年',birthday,'lunar.getBaZi()', lunar.getBaZi())
      bazi = lunar.getBaZi().splice(0, 1);
    }
  }
  return bazi.join(',');
}
class RouterService extends Service {
  /**
   * 根据分页和搜索条件获取
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条
   */
  async getPage(where, page, pageSize) {
    return this.ctx.model[ModelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
    });
  }

  // 所有列表
  async allList(where) {
    return this.ctx.model[ModelName].findAll({
      where,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
    });
  }
  async findOne(id) {
    return this.ctx.model[ModelName].findOne({
      where: {
        id,
      },
    });
  }

  /**
   * 创建
   * @param {*} data 角色信息
   */
  async create(data) {

    return await this.ctx.model[ModelName].create({
      ...data,
      bazi: getBaZiValue(data),
    });


  }

  /**
   * 根据ID修改
   * @param {Number} id ID
   * @param {Object} data 要修改的信息
   */
  async update(id, data) {
    return await this.ctx.model[ModelName].update({
        ...data,
        bazi: getBaZiValue(data),
    }, { where: { id } });
  }

  /**
   * 根据id删除
   * @param {Number}
   */
  async deleteById(id) {
    return await this.ctx.model[ModelName].destroy({ where: { id } });
  }
}

module.exports = RouterService;
